import random
import time
import uiautomation as auto
from functools import wraps
from vjiajia_utils.general_utils import is_debugging

def random_wait(min_time, max_time):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            # 如果是调试模式，等待时间为0
            wait_time = 0 if is_debugging() else random.uniform(min_time, max_time)
            args[0]._log(f"🎯 延迟时间: {wait_time:.2f}秒")  # 打印实际延迟时间
            if wait_time > 0:  # 只有非调试模式才实际等待
                time.sleep(wait_time)
            return result
        return wrapper
    return decorator

class WeChatBaseOperations:
    def __init__(self, log_fun, phone_number, name, apply_msg, prefix, tag):
        self._log = log_fun
        self.wechat_window_class_name = None
        self.wechat_window = None
        self.phone_number = phone_number
        self.name = name
        self.apply_msg = apply_msg
        self.prefix = prefix
        self.tag = tag
        self.sidebar_btns = []
        self._debug_mode = is_debugging()
        if self._debug_mode:
            self._log("⚠️ 调试模式激活 - 所有延时操作将被禁用")
    

    def print_control_tree(self,root_control, max_depth=5):
        """递归打印控件树"""
        for control, depth in auto.WalkControl(root_control, maxDepth=max_depth):
            indent = "  " * depth
            print(f"{indent}{control.ControlTypeName} - {control.Name}")

    @random_wait(0.3, 0.8)
    def _click_wechat_blank(self):
        self._log("点击微信空白处")
        if not self.wechat_window or not self.wechat_window.Exists():
            self._activate_window()
        
        if self.wechat_window.Exists():
            rect = self.wechat_window.BoundingRectangle
            x = rect.left + random.randint(1, 50)
            y = rect.top + random.randint(1, 50)
            auto.Click(x, y)

    def _human_type(self, control, text):
        """
        在控件中输入文本，调试模式下一次性输入所有文本
        """
        self._log(f"输入: {text}")
        if self._debug_mode:
            control.SendKeys(text)
            self._log("📋 调试状态，一次性输入所有文本")
        else:
            # 生产模式：模拟人类逐个字符输入
            for char in text:
                control.SendKeys(char)
                delay = random.uniform(0.1, 0.3)
                self._log(f"⌛ 字符输入延迟: {delay:.2f}秒")
                time.sleep(delay)

    def _human_click(self, control, min_time=1, max_time=2):
        self._log("模拟人类点击")
        delay = 0 if self._debug_mode else random.uniform(min_time, max_time)
        self._log(f"🕒 点击延迟: {delay:.2f}秒")
        if delay > 0:
            time.sleep(delay)
        control.Click()

    def _find_all_edit_controls(self, control):
        """使用 WalkControl 查找所有输入框"""
        self._log("查找所有输入框")
        
        # 使用 WalkControl 遍历所有子控件，并过滤出 EditControl 类型
        edit_controls = [
            c for c, _ in auto.WalkControl(control, maxDepth=10)
            if isinstance(c, auto.EditControl)
        ]
        
        self._log(f"找到 {len(edit_controls)} 个输入框")
        return edit_controls
    
    def _recursive_find_control(self, root_control, control_type, name):
        """使用 WalkControl 但手动过滤结果"""
        for control, _ in auto.WalkControl(root_control, maxDepth=15):
            #self._log(f"查找控件--{control.ControlTypeName}--{control.Name}")
            if isinstance(control, control_type) and control.Name == name:
                return control
        return None

    def is_add_friend_busy(self, wechat_window):
        for control, depth in auto.WalkControl(wechat_window, maxDepth=10):
            if isinstance(control, auto.TextControl) and "频繁" in control.Name:
                self._log("找到频繁添加提示")
                return True
            else:
                self._log("未找到频繁添加提示")

        return False
    def _activate_wechat(self):
        self._log("激活微信窗口")
        self.wechat_window = auto.WindowControl(Name="微信")
        if self.wechat_window.Exists():
            self.wechat_window.SetFocus()
            self.wechat_window.SetActive()
            return True
        else:
            self._log("未找到微信窗口！")
            return False
        
    @random_wait(1, 2)
    def _random_click_sidebar(self):
        """随机点击侧边栏按钮"""
        self._log("随机点击侧边栏")
        random.shuffle(self.sidebar_btns)
        
        for btn_name in self.sidebar_btns:
            self._log(f"寻找侧边栏--{btn_name}")
            btn = auto.ButtonControl(Name=btn_name)
            if btn.Exists():
                self._log(f"随机点击侧边栏--{btn_name}")
                self._human_click(btn)
                return True
        return False
    
    def _switch_to_contacts(self):
        """切换到通讯录"""
        self._log("切换到通讯录")
        contacts_btn = auto.ButtonControl(Name="通讯录")
        if contacts_btn.Exists():
            self._human_click(contacts_btn)
            return True
        return False
    
    def _switch_to_chatlist(self):
        """切换到聊天列表"""
        self._log("切换到聊天页面")
        chatlist_btn = auto.ButtonControl(Name="微信")
        if chatlist_btn.Exists():
            self._human_click(chatlist_btn)
            return True
        return False
    
    def click_sidebar_entry(self):
        raise NotImplementedError("子类必须实现此方法")

    def add_friend(self):
        raise NotImplementedError("子类必须实现此方法")